package com.hadoop.project.utils;

import com.hadoop.project.entity.constant.PreProcessingDataModifier;
import com.hadoop.project.entity.hbase.*;
import com.hadoop.project.entity.po.TabRank;
import com.hadoop.project.entity.po.UserFlavor;
import com.hadoop.project.entity.po.VideoRank;
import com.hadoop.project.entity.hbase.ProcessRes;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Alexmaodali
 * @usage:大数据计算
 */
public class Processor extends PreProcessingDataModifier {

    public static ProcessRes processHBaseData(HBaseResult hBaseResult) {
        if (needResolve) {
            hBaseResult = preProcessingData(hBaseResult);
        }

        // 处理VideoRank
        Map<String, Long> videoCountMap = new HashMap<>();
        for (UserLog userLog : hBaseResult.getUserLogList()) {
            String vid = userLog.getVid();
            videoCountMap.put(vid, videoCountMap.getOrDefault(vid, 0L) + 1);
        }
        // List<VideoRank> videoRankList = videoCountMap.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).map(entry -> VideoRank.builder().videoId(entry.getKey()).views(entry.getValue()).build()).collect(Collectors.toList());
        List<VideoRank> videoRankList = videoCountMap.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).map(entry -> VideoRank.builder().vid(Long.valueOf(entry.getKey())).views(entry.getValue()).build()).collect(Collectors.toList());
        long videoId = 1;
        for (VideoRank vr : videoRankList) {
            vr.setId(videoId++);
        }

        // 处理TabRank
        Map<String, String> tidToTname = hBaseResult.getTabList().stream().collect(Collectors.toMap(Tab::getTid, Tab::getTname));

        Map<String, Long> tnameCountMap = new HashMap<>();
        for (Video video : hBaseResult.getVideoList()) {
            String[] tids = video.getTabs().split(",");
            for (String tid : tids) {
                String tname = tidToTname.get(tid);
                if (tname != null) {
                    tnameCountMap.put(tname, tnameCountMap.getOrDefault(tname, 0L) + 1);
                }
            }
        }

        List<TabRank> tabRankList = hBaseResult.getTabList().stream().map(tab -> {
            String tname = tab.getTname();
            Long cnt = tnameCountMap.getOrDefault(tname, 0L);
            return TabRank.builder().tname(tname).cnt(cnt).build();
        }).collect(Collectors.toList());
        tabRankList.sort(Comparator.comparingLong(TabRank::getCnt).reversed());
        long tabId = 1;
        for (TabRank tr : tabRankList) {
            tr.setId(tabId++);
        }

        // 处理UserFlavor
        // 1. 重新计算正确的标签总次数（所有用户观看次数总和）
        Map<String, Long> totalTagCountMap = new HashMap<>();
        for (UserLog userLog : hBaseResult.getUserLogList()) {
            String vid = userLog.getVid();
            Video video = hBaseResult.getVideoList().stream().filter(v -> v.getVid().equals(vid)).findFirst().orElse(null);
            if (video == null) continue;
            String[] tids = video.getTabs().split(",");
            for (String tid : tids) {
                String tname = tidToTname.get(tid);
                if (tname != null) {
                    totalTagCountMap.put(tname, totalTagCountMap.getOrDefault(tname, 0L) + 1);
                }
            }
        }

        // 2. 统计用户标签观看次数
        Map<String, Map<String, Long>> userTagCountMap = new HashMap<>();
        for (UserLog userLog : hBaseResult.getUserLogList()) {
            String uid = userLog.getUid();
            String vid = userLog.getVid();
            Video video = hBaseResult.getVideoList().stream().filter(v -> v.getVid().equals(vid)).findFirst().orElse(null);
            if (video == null) continue;
            String[] tids = video.getTabs().split(",");
            for (String tid : tids) {
                String tname = tidToTname.get(tid);
                if (tname == null) continue;
                userTagCountMap.computeIfAbsent(uid, k -> new HashMap<>()).merge(tname, 1L, Long::sum);
            }
        }

        List<UserFlavor> userFlavorList = new ArrayList<>();
        for (HBaseUser user : hBaseResult.getHBaseUserList()) {
            String uid = user.getUid();
            Map<String, Long> userTags = userTagCountMap.getOrDefault(uid, new HashMap<>());
            for (String tname : totalTagCountMap.keySet()) {
                Long userCount = userTags.getOrDefault(tname, 0L);
                Long totalCount = totalTagCountMap.getOrDefault(tname, 0L);

                // 修正百分比计算逻辑
                double percent = totalCount == 0 ? 0.0 : (userCount * 100.0) / totalCount;
                String tpercent = String.format("%.1f%%", percent);

                userFlavorList.add(UserFlavor.builder().uid(Long.parseLong(uid)).tname(tname).tpercent(tpercent).build());
            }
        }

        long userFlavorId = 1;
        for (UserFlavor uf : userFlavorList) {
            uf.setId(userFlavorId++);
        }
        userFlavorList.sort((a, b) -> {
            double aVal = Double.parseDouble(a.getTpercent().replace("%", ""));
            double bVal = Double.parseDouble(b.getTpercent().replace("%", ""));
            return Double.compare(bVal, aVal);
        });

        return ProcessRes.builder().tabRankList(tabRankList).videoRankList(videoRankList).userFlavorList(userFlavorList).build();
    }

}
